// subpkg/postDetail/postDetail.js
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
const util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    postDetail: {},
    rePostid: '',
    showGl: false,
    showBuy: false,
    showWant: false,
    showCancel: false,
    isbuyUser: false,
    buyUser: {},
    // 是否收藏
    isLike: false,
    likeBtn: true,
    likeNum: 0,
  },
  toChat() {
    if (wx.getStorageSync('user').status && wx.getStorageSync('user').status == 1) {
      let data = JSON.stringify(this.data.postDetail.userInfo[0])
      wx.navigateTo({
        url: `../../subpkg/chatwx/index?data=${encodeURIComponent(data)}`,
      })
    } else {
      Dialog.confirm({
        title: '温馨提示',
        message: '未认证的用户无法使用该功能，点击确认前往认证',
      })
        .then(() => {
          wx.navigateTo({
            url: '../../subpkg/rz/index',
          })
        })
        .catch(() => {
          // on cancel
        });
    }
  },
  chatToBuy() {
      let data = JSON.stringify(this.data.buyUser)
      wx.navigateTo({
        url: `../../subpkg/chatwx/index?data=${encodeURIComponent(data)}`,
      })
  },
  like(e) {
    // e.currentTarget.dataset.id
    if (!this.data.likeBtn) {
      console.log('频繁重复点击')
      return
    }
    console.log('e.currentTarget.dataset.id', e.currentTarget.dataset.id)
    this.setData({likeBtn:false})
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'quickstartFunctions',
      // 传给云函数的参数
      data: {
        type: 'like',
        likeType: e.currentTarget.dataset.id,
        likeVal: wx.getStorageSync('openid'),
        _id: this.data.postDetail._id,
      },
    }).then((resp) => {
      if (e.currentTarget.dataset.id) {
        Toast.success('已添加收藏!');
        this.setData({
          isLike: true,
          likeBtn:true,
          likeNum: this.data.likeNum += 1
        })
      } else {
        Toast.success('已取消收藏!');
        this.setData({
          isLike: false,
          likeBtn:true,
          likeNum: this.data.likeNum -= 1
        })
      }
    }).catch((e) => {
      console.log('e',e)
    });
  },
  buy() {
    if (wx.getStorageSync('user').status && wx.getStorageSync('user').status == 1) {
      Dialog.confirm({
        title: '温馨提示',
        message: '确认是否购买',
      })
        .then(() => {
          wx.cloud.callFunction({
            name: 'quickstartFunctions',
            data: {
              type: 'buy',
              _id: this.data.postDetail._id,
              openid: wx.getStorageSync('openid'),
            },
          }).then((resp) => {
            console.log('购买',resp)
            Toast.success('购买成功!');
            let t = new Date()
            let obj = {
              sendId: wx.getStorageSync('openid'),
              getId:  this.data.postDetail.openid,
              msg: '商品已被拍下，记得按约定交易',
              time:  t.getTime(),
              creatTime: util.formatTime(t)
            }
            console.log('obj', obj)
            // return
            wx.cloud.callFunction({
              // 需调用的云函数名
              name: 'quickstartFunctions',
              // 传给云函数的参数
              data: {
                type: 'sendMsg',
                obj: obj,
              },
            }).then((resp) => {
              setTimeout(() => {
                wx.switchTab({
                  url: '../../pages/user/index'
                })
              }, 1500);
            }).catch((e) => {
              console.log(e)
            });

          }).catch((e) => {
            console.log('e',e)
          });
  
        })
        .catch(() => {
          // on cancel
        });

    } else {
      Dialog.confirm({
        title: '温馨提示',
        message: '未认证的学生无法使用该功能，点击确认前往认证',
      })
        .then(() => {
          wx.navigateTo({
            url: '../../subpkg/rz/index',
          })
        })
        .catch(() => {
          // on cancel
        });
    }
  },
  deleteApi() {
    Dialog.confirm({
      title: '温馨提示',
      message: '确认是否删除',
    })
      .then(() => {
        
        wx.cloud.callFunction({
          // 需调用的云函数名
          name: 'quickstartFunctions',
          // 传给云函数的参数
          data: {
            type: 'deleteApi',
            _id: this.data.postDetail._id,
          },
        }).then((resp) => {
          Toast.success('删除成功!');
          setTimeout(() => {
            wx.switchTab({
              url: '../../pages/user/index'
            })
          }, 1500);
        }).catch((e) => {
          console.log('e',e)
        });

      })
      .catch(() => {
        // on cancel
      });
  },
  cancelApi() {
    Dialog.confirm({
      title: '温馨提示',
      message: '是否取消订单',
    })
      .then(() => {
        
        wx.cloud.callFunction({
          // 需调用的云函数名
          name: 'quickstartFunctions',
          // 传给云函数的参数
          data: {
            type: 'cancelApi',
            _id: this.data.postDetail._id,
          },
        }).then((resp) => {
          Toast.success('取消订单成功!');
          setTimeout(() => {
            wx.switchTab({
              url: '../../pages/user/index'
            })
          }, 1500);
        }).catch((e) => {
          console.log('e',e)
        });

      })
      .catch(() => {
        // on cancel
      });
  },
  edit() {
    let obj = JSON.stringify(this.data.postDetail)
    wx.navigateTo({
      url: `../../subpkg/setProduct/index?obj=${encodeURIComponent(obj)}`
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      postDetail: JSON.parse(decodeURIComponent(options.detail)),
    })
    console.log('postDetail', this.data.postDetail)
    if (this.data.postDetail.likeList && this.data.postDetail.likeList.includes(wx.getStorageSync('openid'))) {
      this.setData({isLike: true})
    }
    if (this.data.postDetail.likeList) {
      this.setData({likeNum: this.data.postDetail.likeList.length})
    }
    
    
    // 没有被购买，才显示功能按钮
    if (!this.data.postDetail.buyId) {
      // 自己发布的显示管理按钮
      if (this.data.postDetail.openid == wx.getStorageSync('openid')) {
        this.setData({showGl: true})
      } else {
        // 别人发布的显示咨询和购买
        this.setData({showWant: true})
        if (this.data.postDetail.proType == '卖出') {
          this.setData({showBuy: true})
        }
      }
    } else {
      wx.cloud.callFunction({
        // 需调用的云函数名
        name: 'quickstartFunctions',
        // 传给云函数的参数
        data: {
          type: 'getUser',
          openid: this.data.postDetail.buyId,
        },
      }).then((resp) => {
        console.log('购买人的信息',resp.result.data[0])
        this.setData({buyUser: resp.result.data[0],isbuyUser: true})
        if (this.data.postDetail.openid == wx.getStorageSync('openid')) {
          this.setData({showCancel: true})
        } 
      }).catch((e) => {
        console.log('e',e)
      });
    }
    wx.setNavigationBarTitle({
      title: '商品详情',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // console.log('asd',false&&false)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})